package com.itheima.tlias.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.itheima.tlias.pojo.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;

@RestController
public class CaptchaController {

    @Autowired
    private DefaultKaptcha mathKaptcha; // 注意注入的是 MathKaptchaConfig 中定义的那个 bean

    @GetMapping("/captcha")
    public Result getCaptcha(HttpServletRequest request) throws Exception {
        String code = mathKaptcha.createText(); // 假设是 "5 + 3 = 8"

        // 分离题目和答案
        String[] parts = code.split("=");
        String question = parts[0] + "="; // 得到 "5 + 3 ="
        String answer = parts[1].trim();   // 得到 "8"

        // 把答案保存到 session
        request.getSession().setAttribute("captcha", answer);

        // ⚠️ 关键点：生成图片时使用的是只有题目的字符串
        BufferedImage image = mathKaptcha.createImage(question);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", outputStream);

        String base64Image = "data:image/png;base64," + Base64.getEncoder().encodeToString(outputStream.toByteArray());
        return Result.success(base64Image);
    }
}